function drawIGrid(obj,grid)
%DRAWIGRID Summary of this function goes here
%   Detailed explanation goes here

% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal


%we need to recover handle structure so that we can interact with
%TreeWidget.
handles=guidata(obj.m_Figure);
if isfield(obj.m_inputGrids,grid)
%does the graphical representation exist? Delete it.
if isfield(obj.m_inputGrids.(grid),'handle')
    if ishandle(obj.m_inputGrids.(grid).handle)
        delete(obj.m_inputGrids.(grid).handle);
    end
end

%retrieve needed data from TreeWidget
xmin=handles.TreeWidget.getValue('Xmin',grid);
ymin=handles.TreeWidget.getValue('Ymin',grid);
n=handles.TreeWidget.getValue('Nx',grid);
m=handles.TreeWidget.getValue('Ny',grid);
dx=handles.TreeWidget.getValue('X Step',grid);
dy=handles.TreeWidget.getValue('Y Step',grid);
xmax=dx*(n-1)+xmin;
ymax=dy*(m-1)+ymin;
x=linspace(xmin,xmax,n);
y=linspace(ymin,ymax,m);

%determine the drawing method.
switch obj.m_inputGrids.(grid).method
    case 'image'
    %depending on the kind of grid, use single colormap.
    switch grid
        case 'BATHYMETRY'
            seamap=obj.getGradient(obj.m_iGridsProp.(grid).seamap.c1,...
                obj.m_iGridsProp.(grid).seamap.c2);
            landmap=obj.getGradient(obj.m_iGridsProp.(grid).landmap.c1,...
                obj.m_iGridsProp.(grid).landmap.c2);
            img=ind2bathym(obj.m_inputGrids.(grid).data,seamap,landmap,...
                handles.jProgressBar,handles.jStatusBar);
        otherwise
            map=obj.getGradient(obj.m_iGridsProp.(grid).map.c1,...
                obj.m_iGridsProp.(grid).map.c2);
            img=ind2map(obj.m_inputGrids.(grid).data,map,...
                handles.jProgressBar,handles.jStatusBar);
    end
    %draw image.
    obj.m_inputGrids.(grid).handle=image('Parent',obj.m_inputAx,'XData',...
        x,'YData',y,'CData',img,'CDataMapping','scaled','Tag',grid);
    alpha(obj.m_inputGrids.(grid).handle,obj.m_inputGrids.(grid).alpha);
    %display info. Drawing complete.
    handles.jProgressBar.setVisible(0);
    handles.jStatusBar.setText('Drawing complete.');
    
    case 'contour'
    
    %contourplots are different. We need to modify every single line.
    [C,h]=contour(obj.m_inputAx,x,y,obj.m_inputGrids.(grid).data);
    clear C;
    
    
    lvllines=get(h,'LevelList');
    switch grid
        case 'BATHYMETRY'
      
    wlines=lvllines(lvllines<0);
    if length(wlines)<2
        seamap=obj.m_inputGrids.(grid).seamap.c1;
    else
        seamap=obj.getGradient(obj.m_iGridsProp.(grid).seamap.c2,...
        obj.m_iGridsProp.(grid).seamap.c1,length(wlines));
    end
    llines=lvllines(lvllines>=0);
    if length(llines)<2
        landmap=obj.m_iGridsProp.(grid).landmap.c1;
    else
        landmap=obj.getGradient(obj.m_iGridsProp.(grid).landmap.c1,...
        obj.m_iGridsProp.(grid).landmap.c2,length(llines));
    end
    map=[seamap;landmap];
        otherwise
            map=obj.getGradient(obj.m_iGridsProp.(grid).map.c1,...
        obj.m_iGridsProp.(grid).map.c2,length(lvllines));
    end
    a=get(h,'Children');
    
    set(handles.jProgressBar,'StringPainted','on',...
        'Minimum',0, 'Maximum',length(a), 'Value',0);
    handles.jStatusBar.setText('Drawing grid...');
	handles.jProgressBar.setValue(0);
    handles.jProgressBar.setVisible(1);
    
    for k=1:length(a)
    %only consider the children that are patch objects
        if strcmp(get(a(k),'Type'),'patch')
        %'UserData' indicates the elevation associated with a patch
            pos=get(a(k),'UserData');
            if any(lvllines'==pos) %if pos is found in lvllines
                color=map(lvllines'==pos,:);
            else
                color='none';
            end
            set(a(k),'EdgeColor',color);
        end
        handles.jProgressBar.setValue(k);
    end

    
    obj.m_inputGrids.(grid).handle=h;
    clear h;
    handles.jStatusBar.setText('Drawing complete.');
    
    case 'quiver' %Only available for Current and Wind!!
        data=obj.m_inputGrids.(grid).data;
        U=data(:,:,1);
        V=data(:,:,2);
        [X,Y]=meshgrid(x,y);
        %reduce data... 
        U(1:2:end,:)=[];
        U(:,1:2:end)=[];
        V(1:2:end,:)=[];
        V(:,1:2:end)=[];
        X(1:2:end,:)=[];
        X(:,1:2:end)=[];
        Y(1:2:end,:)=[];
        Y(:,1:2:end)=[];
        %colorQuiver uses too much RAM. Optimization required.
        obj.m_inputGrids.(grid).handle=quiver(obj.m_inputAx,X,Y,U,V);
        %map=obj.getGradient(obj.m_iGridsProp.(grid).map.c1,...
        %    obj.m_iGridsProp.(grid).map.c2);
        %obj.m_inputGrids.(grid).handle=colorQuiver(obj.m_inputAx,X,Y,U,V,...
        %    map,handles.jProgressBar,handles.jStatusBar);
end
%TODO: if we have several input grids, order them with uistack
end

function img=ind2bathym(data,seamap,landmap,pBar,sBar)

%locate sea and land areas
sea=nan(size(data));
land=nan(size(data));
sea(data<0)=data(data<0);
land(data>=0)=data(data>=0);

sea=sea/min(min(sea));
land=land/max(max(land));

sea=round(sea.*size(seamap,1));
land=round(land.*(size(landmap,1)-1));

rs=zeros(size(data));
gs=rs;
bs=rs;

rl=rs;
gl=rs;
bl=rs;

l=size(seamap,1)+size(landmap,1)-1;
% Add a progress-bar to left side of standard MJStatusBar container
warning('off','MATLAB:hg:JavaSetHGPropertyParamValue');
set(pBar,'StringPainted','on','Minimum',0, 'Maximum',l+1, 'Value',0);
sBar.setText('Drawing grid...');
pBar.setValue(0);
pBar.setVisible(1);
%get RGB values
for j=1:size(seamap,1)
    rs(sea==j)=seamap(j,1);
    gs(sea==j)=seamap(j,2);
    bs(sea==j)=seamap(j,3);
    pBar.setValue(j);
end
%RGB value for sea=0 is first color of colormap
rs(sea==0)=seamap(1,1);
gs(sea==0)=seamap(1,2);
bs(sea==0)=seamap(1,3);

for k=2:size(landmap,1)
    rl(land==(k-1))=landmap(k,1);
    gl(land==(k-1))=landmap(k,2);
    bl(land==(k-1))=landmap(k,3);
    pBar.setValue(j+k);
end
%RGB value for 0 is first color of land colormap
rl(land==0)=landmap(1,1);
gl(land==0)=landmap(1,2);
bl(land==0)=landmap(1,3);

%convert nan to 0 so we can sum land and sea matrix.
rs(isnan(sea))=0;
gs(isnan(sea))=0;
bs(isnan(sea))=0;
rl(isnan(land))=0;
gl(isnan(land))=0;
bl(isnan(land))=0;

r=rs+rl;
g=gs+gl;
b=bs+bl;
pBar.setValue(l+1);
img=cat(3,r,g,b);

function img=ind2map(data,map,pBar,sBar)

%new method

data=data/max(max(data));

data=round(data.*(size(map,1)));

r=zeros(size(data));
g=r;
b=r;

l=size(map,1);
% Add a progress-bar to left side of standard MJStatusBar container
set(pBar,'StringPainted','on','Minimum',0, 'Maximum',l+1, 'Value',0);
sBar.setText('Drawing grid...');
pBar.setValue(0);
pBar.setVisible(1);
%get RGB values
for j=1:l
    r(data==j)=map(j,1);
    g(data==j)=map(j,2);
    b(data==j)=map(j,3);
    pBar.setValue(j);
end
%RGB value for data=0 is first color of colormap (maybe white?)
r(data==0)=map(1,1);
g(data==0)=map(1,2);
b(data==0)=map(1,3);

pBar.setValue(l+1);
img=cat(3,r,g,b);

function hquiver=colorQuiver(ax,x,y,u,v,map,pBar,sBar)
%draws a colored quiver plot using custom colormap. Returns a structure
%with all the handles needed to draw the map.

%actual code (to be modified for 1.0) adapted from cquiver.m found in
%FileExchange, by Nicholas Howe.
[th,z] = cart2pol(u,v);

maxd = sqrt(max(u(:).^2+v(:).^2));

nclr = size(map,1);
cont = linspace(0,maxd,nclr+1);
cont(1) = [];

arrow=0.40;
scalelength = 1;
l=length(cont);
set(pBar,'StringPainted','on','Minimum',0,'Maximum',l,'Value',0);
sBar.setText('Drawing grid...');
pBar.setValue(0);
pBar.setVisible(1);
for j=1:l

  if j==1
   mask=find(z<cont(j));
  elseif j==length(cont)
   mask=find(z>=cont(j-1));
  else
   mask=find(z<cont(j) & z>=cont(j-1));
  end
  mask = mask';

  % Center vectors over grid points
  [u,v] = pol2cart(th(mask),scalelength);
  xstart=x(mask)-0.5*u;
  xend=x(mask)+0.5*u;
  ystart=y(mask)-0.5*v;
  yend=y(mask)+0.5*v;

  % Get x coordinates of each vector plotted
  lx = [xstart; ...
       xstart+(1-arrow/3)*(xend-xstart); ...
       xend-arrow*(u+arrow*v); ...
       xend; ...
       xend-arrow*(u-arrow*v); ...
       xstart+(1-arrow/3)*(xend-xstart); ...
       nan(size(xstart))];

  % Get y coordinates of each vector plotted
  ly = [ystart; ...
       ystart+(1-arrow/3)*(yend-ystart); ...
       yend-arrow*(v-arrow*u); ...
       yend; ...
       yend-arrow*(v+arrow*u); ...
       ystart+(1-arrow/3)*(yend-ystart); ...
       nan(size(ystart))];

  % Plot the vectors
  tag=sprintf('line%d',j);
  hquiver.(tag)=line('Parent',ax,'XData',lx(:),'YData',ly(:),...
      'Color',map(j,:));
  pBar.setValue(j);
end